package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user/addressBook")
@ApiOperation("C端-地址簿相关接口")
@Slf4j
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;


    /**
     * 查询当前登录用户的所有地址信息
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("查询当前登录用户的所有地址信息")
    public Result<List<AddressBook>> list() {
        return Result.success(addressBookService.list());
    }

    /**
     * 新增地址
     * @param addressBook
     * @return
     */
    @PostMapping
    @ApiOperation("新增地址")
    public Result<String> add(@RequestBody AddressBook addressBook) {
        log.info("要添加的地址信息：{}", addressBook);
        addressBookService.add(addressBook);
        return Result.success("新增成功");
    }

    /**
     * 设置默认地址
     * @param request
     * @return
     */
    @PutMapping("/default")
    @ApiOperation("设置默认地址")
    public Result<String> setDefault(@RequestBody Map<String, Long> request) {
        Long id = request.get("id");
        log.info("要设置默认地址的id：{}", id);
        addressBookService.setDefault(id);
        return Result.success("设置成功");
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询地址")
    public Result<AddressBook> queryById(@PathVariable Long id) {
        return Result.success(addressBookService.queryById(id));
    }

    /**
     * 根据id修改地址
     * @param addressBook
     * @return
     */
    @PutMapping
    @ApiOperation("根据id修改地址")
    public Result<String> updateById(@RequestBody AddressBook addressBook) {
        log.info("要保存的地址簿信息：{}", addressBook);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookService.updateById(addressBook);
        return Result.success("更新成功");
    }

    /**
     * 根据id删除地址
     * @param id
     * @return
     */
    @DeleteMapping
    @ApiOperation("根据id删除地址")
    public Result<String> deleteById(Long id) {
        log.info("要删除的地址簿id：{}", id);
        addressBookService.deleteById(id);
        return Result.success("删除成功");
    }

    /**
     * 查询默认地址
     * @return
     */
    @GetMapping("/default")
    @ApiOperation("查询默认地址")
    public Result<AddressBook> queryDefault() {
        return Result.success(addressBookService.queryDefault());
    }

}
